package top.kikt.book.core.handlers.common

import org.jsoup.Jsoup
import org.jsoup.nodes.Document
import top.kikt.book.core.base.BookChapterHandler
import top.kikt.book.core.base.BookMetaHandler
import top.kikt.book.core.entity.ChapterMetaEntity
import java.nio.charset.Charset

abstract class BaseBookHandler : BookHandlerContext() {

    fun chromeHeaders(): Map<String, String> {
        return mapOf(
            "User-Agent" to "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/123.0.0.0 Safari/537.36 Edg/123.0.0.0",
            "Accept" to "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            "Cache-Control" to "max-age=0",
            "Sec-Ch-Ua" to """"Microsoft Edge";v="123", "Not:A-Brand";v="8", "Chromium";v="123"""",
            "Sec-Ch-Ua-Mobile" to "?0",
            "Sec-Ch-Ua-Platform" to "macOS",
            "Upgrade-Insecure-Requests" to "1",
        )
    }

    override fun createBookMetaHandler(): BookMetaHandler {
        return this
    }

    override fun createBookChapterHandler(): BookChapterHandler {
        return this
    }

    override fun isSupported(): Boolean {
        return true
    }

    override fun searchBook(keyword: String): List<String> {
        return emptyList()
    }

    fun ChapterMetaEntity.toDocument(charset: Charset? = null): Document? {
        val currentCharset = charset ?: this@BaseBookHandler.charset
        val byteStream = get(url).body?.byteStream() ?: return null
        return Jsoup.parse(byteStream, currentCharset.name(), url)
    }
}
